package kr.co.redcircle.service.oAuth.model;

import java.util.Hashtable;
import java.util.List;


import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;

public class SNSCommandCollection extends Hashtable<String, ICommand>{

	private static final long serialVersionUID = 2868310624527112044L;

	@SuppressWarnings("unchecked")
	public SNSCommandCollection(Element moduleElement) {
		try {
			String targetid = moduleElement.getAttributeValue("id");
			Element commandElements = (Element)XPath.selectSingleNode(moduleElement, "//module[@id='"+targetid+"']/collection[@id='commands']");
			List<Element> keyList = commandElements.getChildren();
			
			for (Element targetElement : keyList){
				
				String keyID = targetElement.getAttributeValue("id");
				String keyMethod = targetElement.getAttributeValue("method");
				String keyDescription = targetElement.getAttributeValue("desc");
				String keyClass = targetElement.getChildText("class");
				String keyVALUE = targetElement.getChildText("url");
				Element templateElement = targetElement.getChild("template");
				
				Class<?> tgrCommandClass = Class.forName(keyClass);
				Object instanceObject = tgrCommandClass.newInstance();
				ICommand tgrCommand = (ICommand)instanceObject;
				tgrCommand.setKeyID(keyID);
				tgrCommand.setKeyMethod(keyMethod);
				tgrCommand.setKeyDescription(keyDescription);
				tgrCommand.setKeyVALUE(keyVALUE);
				
				System.out.println(targetid + " :: command ==> " + keyID + " :: " + templateElement);
				if (templateElement != null) tgrCommand.setTemplate(buildTemplate(templateElement));
				
				this.put(keyID, tgrCommand);
				
			}
			
			
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	private ITemplate buildTemplate(Element child) {
		ITemplate template = null;
		if (child != null){
			String contentsString = child.getChildText("contents");
			template = new DefaultTemplate(contentsString);
		}
		
		return template;
	}

	@Override
	public String toString() {
		return "SNSCommandCollection [keys()=" + keys() + "]";
	}

}
